package org.lib93.com.libSkin

import android.util.AttributeSet
import android.util.Log
import android.view.View
import org.lib93.com.libSkin.utils.*
import org.lib93.com.libSkin.view.SkinAttribute
import org.lib93.com.libSkin.view.SkinView

class SkinViewManager private constructor() {
    private val mAttributes = listOf<String>( //需要替换资源的属性
        BACKGROUND,
        SRC ,
        TEXTCOLOR,
        DRAWABLELEFT,
        DRAWABLETOP,
        DRAWABLERIGHT,
        DRAWABLEBOTTOM
            )
    private val mSkinViews = mutableListOf<SkinView>()//缓存所有的view
    companion object {
        @Volatile private var instance: SkinViewManager? = null
        fun getInstance() =
            instance ?: synchronized(this) {
                instance ?: SkinViewManager().also { instance = it }
            }
    }
    fun add(view:View,attrs: AttributeSet){
        Log.d("lib093", "add ===="+view.javaClass.name)
        var attrslist = mutableListOf<SkinAttribute>()
        var size = attrs.attributeCount-1
        for (i in 0..size){
            val attributeName = attrs.getAttributeName(i)
            if (mAttributes.contains(attributeName)){
                val attributeValue = attrs.getAttributeValue(i)


                if (attributeValue.startsWith("#"))
                    continue //写死数据不做处理
                var resId: Int = 0
                if (attributeValue.startsWith("?")){
                    //?开头
                    var attrId = attributeValue.substring(1).toInt()
                    var list = IntArray(1)
                    list[0] = attrId
                    resId = SkinThemeManager.getInstance().getResId(view.context, list)[0]
                }else{
                    //@开头
                    resId = attributeValue.substring(1).toInt()
                }
                attrslist.add(SkinAttribute(attributeName,resId))
            }
        }
        if (!attrslist.isEmpty()|| view is SkinViewSupport){
            var skinView = SkinView(view,attrslist)
            skinView.apply()
            mSkinViews.add(skinView)
        }
    }
    //进行换肤
    fun apply(){
        if (mSkinViews.isEmpty())
            return
        mSkinViews.forEach {
            it.apply();
        }
    }
}